package mysql

import "C"
import (
	"context"
	"fmt"
	"time"

	"gitee.com/krio/ginc/example/core/lib/conf"
	adminConfigModel "gitee.com/krio/ginc/example/internal/admin/config/model"
	adminDynamicEnumModel "gitee.com/krio/ginc/example/internal/admin/dynamic/enum/model"
	adminDynamicFieldModel "gitee.com/krio/ginc/example/internal/admin/dynamic/field/model"
	adminMenuModel "gitee.com/krio/ginc/example/internal/admin/menu/model"
	adminUserAccountModel "gitee.com/krio/ginc/example/internal/admin/user/account/model"
	adminUserLoginLogModel "gitee.com/krio/ginc/example/internal/admin/user/login_log/model"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/core"
	"github.com/xormplus/xorm"
)

var (
	x *xorm.Engine
)

// InitMysql 初始化数据库mysql
// xorm: http://xorm.topgoer.com/
func InitMysql() error {
	var (
		url = conf.C.Mysql.URL
		err error
	)
	x, err = xorm.NewEngine("mysql", url)
	if err != nil {
		return fmt.Errorf("连接mysql失败: %s %+v", url, err)
	}
	maxIdle := conf.C.Mysql.MaxIdle
	x.SetConnMaxLifetime(2 * time.Hour)
	x.SetMaxOpenConns(200)
	x.SetMaxIdleConns(maxIdle)
	x.SetTableMapper(core.NewPrefixMapper(core.GonicMapper{}, ""))
	x.SetColumnMapper(core.GonicMapper{})
	// 注册sql模板文件
	//stplUrl := conf.C.Mysql.FPath + "/stpl"
	//err = x.RegisterSqlTemplate(xorm.Pongo2(stplUrl, ".stpl"))
	//if err != nil {
	//	return nil, fmt.Errorf("注册mysql模板失败: %s %+v", stplUrl, err)
	//}

	if err = x.Ping(); err != nil {
		return fmt.Errorf("ping-mysql失败: %+v", err)
	}
	// 自动注册表
	err = x.Sync2(
		new(adminMenuModel.AdminMenu),
		new(adminUserAccountModel.AdminUserAccount),
		new(adminConfigModel.AdminConfig),
		new(adminUserLoginLogModel.AdminUserLoginLog),
		new(adminDynamicFieldModel.DynamicField),
		new(adminDynamicEnumModel.DynamicEnum),
		new(adminDynamicEnumModel.DynamicEnumValue),
	)
	if err != nil {
		return fmt.Errorf("mysql自动注册失败: %+v", err)
	}
	x.ShowSQL(conf.C.Mysql.ShowSQL)

	return nil
}

func Orm(ctx context.Context) *xorm.Engine {
	return x
}
